package com.example.forum.commons.jwt;


import com.alibaba.fastjson.JSONException;
import com.example.forum.commons.tools.StringUtil;
import com.example.forum.vo.CurrentUser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
* @author liucheng
* @since 2020/01/15
* JwtHelper
*/
@Component
public class JwtHelper {

   @Value("${jwtSecret}")
   private String SECRET;

   @Value("${jwtExpire}")
   private Long EXPIRATION_TIME;

   private final String TOKEN_PREFIX = "Bearer";

    //创建token
   public JwtTokenResult generateToken(LoginUserModel customClaims) throws JSONException {
       Map<String, Object> claims = new HashMap<String, Object>();
       claims.put("userName", customClaims.getUserName());
       claims.put("userId", customClaims.getUserId());
       claims.put("normalPermissions", customClaims.getNormalPermissions());
       claims.put("permissions", customClaims.getPermissions());
       claims.put("realName", customClaims.getRealName());
       claims.put("role", customClaims.getRole());

       Calendar c = Calendar.getInstance();
       c.setTime(new Date());
       c.add(Calendar.SECOND, EXPIRATION_TIME.intValue());
       Date d = c.getTime();
       String jwt = Jwts.builder()
               .setClaims(claims)
               .setExpiration(d)
               .signWith(SignatureAlgorithm.HS512, SECRET)
               .compact();
       JwtTokenResult json = new JwtTokenResult();
       json.setAccess_token(TOKEN_PREFIX + " " + jwt);
       json.setExpire_time(new SimpleDateFormat("yyyy-MM-dd HH:ss:mm").format(d));
       json.setToken_type(TOKEN_PREFIX);
       json.setLoginUser(customClaims);
       return json;
   }

   //验证token
   public Boolean validateTokenAndGetClaims(String token) {
       try {
           if (StringUtil.isEmpty(token)) {
               return false;
           }
           Map<String, Object> body = Jwts.parser()
                   .setSigningKey(SECRET)
                   .parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
                   .getBody();
           return true;
       } catch (Exception e) {
           return false;
       }
   }

   //根据token获取用户信息
   public CurrentUser getJwtTokenResult(String token) {
       try {
           if (StringUtil.isEmpty(token)) {
               return null;
           }
           Map<String, Object> body = Jwts.parser()
                   .setSigningKey(SECRET)
                   .parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
                   .getBody();

           CurrentUser currentUser=new CurrentUser();
           currentUser.setId(body.get("userId").toString());
           currentUser.setUsername(body.get("userName").toString());
           currentUser.setPermissions(StringUtil.toString(body.get("permissions")));
           currentUser.setRole(StringUtil.toString(body.get("role")));
           return currentUser;
       } catch (Exception e) {
           return null;
       }
   }


   public  Map<String, String>getJwtTokenUserIdAndSign(String token) {
       try {
           if (StringUtil.isEmpty(token)) {
               return null;
           }
           Map<String, Object> body = Jwts.parser()
                   .setSigningKey(SECRET)
                   .parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
                   .getBody();
           String auth = token.split(" ")[1];
           var jwtArr = auth.split("\\.");

           Map<String, String> result= new HashMap<>();
           result.put("userId",body.get("userId").toString());
           result.put("sign",jwtArr[2]);
           return  result;
       } catch (Exception e) {
           return null;
       }
   }
}